// courier-update.js - 物流更新模块
// 等待apiService和Utils加载完成
function initCourierUpdate() {
    if (window.apiService && window.Utils) {
        const apiService = window.apiService;
        const Utils = window.Utils;

        class CourierUpdate {
    constructor() {
        this.initialize();
    }

    // 初始化
    initialize() {
        // 检查当前页面
        if (window.location.pathname.includes('/pages/courier/dashboard.html')) {
            this.initCourierDashboard();
        } else if (window.location.pathname.includes('/pages/courier/update.html')) {
            this.initUpdatePage();
        }
    }

    // 初始化物流员仪表盘
    async initCourierDashboard() {
        try {
            // 获取物流员的包裹列表
            const response = await apiService.fetch('/api/courier/packages', {
                method: 'GET'
            });

            if (response.success) {
                this.renderPackageList(response.data);
            } else {
                alert('获取包裹列表失败');
            }
        } catch (error) {
            alert('系统错误，请稍后再试');
        }
    }

    // 初始化更新页面
    async initUpdatePage() {
        // 获取包裹ID
        const packageId = Utils.getUrlParam('packageId');
        if (!packageId) {
            Utils.showNotification('未指定包裹ID', 'error');
            return;
        }

        try {
            // 获取包裹详情
            const response = await apiService.fetch(`/api/packages?id=${packageId}`, {
                method: 'GET'
            });

            if (response.success && response.data) {
                this.renderPackageDetails(response.data);
                // 绑定更新按钮事件
                this.bindUpdateButton(packageId);
            } else {
                Utils.showNotification('获取包裹详情失败', 'error');
            }
        } catch (error) {
            console.error('初始化更新页面失败:', error);
            Utils.showNotification('系统错误，请稍后再试', 'error');
        }
    }

    // 渲染包裹列表
    renderPackageList(packages) {
        const container = document.getElementById('package-list');
        if (!container) return;

        if (packages.length === 0) {
            container.innerHTML = `
                <div class="card">
                    <div class="card-header">
                        <h2>我的包裹</h2>
                    </div>
                    <div class="no-data">
                        <p>暂无包裹信息</p>
                    </div>
                </div>
            `;
            return;
        }

        // 状态样式映射
        const statusClassMap = {
            'pending': 'status-pending',
            'in-transit': 'status-in-transit',
            'delivered': 'status-delivered',
            'cancelled': 'status-cancelled'
        };

        let html = `
            <div class="card">
                <div class="card-header">
                    <h2>我的包裹</h2>
                </div>
                <div class="table-container">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>运单编号</th>
                                <th>状态</th>
                                <th>收件人</th>
                                <th>目的地</th>
                                <th>预计送达</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
        `;

        packages.forEach(pkg => {
            html += `
                <tr>
                    <td>${pkg.id}</td>
                    <td><span class="status-badge ${statusClassMap[pkg.status] || ''}">${this.getStatusText(pkg.status)}</span></td>
                    <td>${pkg.receiver}</td>
                    <td>${pkg.destination}</td>
                    <td>${pkg.estimatedDelivery}</td>
                    <td>
                        <a href="update.html?packageId=${pkg.id}" class="btn-primary">更新状态</a>
                    </td>
                </tr>
            `;
        });

        html += `
                        </tbody>
                    </table>
                </div>
            </div>
        `;

        container.innerHTML = html;
    }

    // 渲染包裹详情
    renderPackageDetails(pkg) {
        const container = document.getElementById('package-details');
        if (!container) return;

        // 状态样式映射
        const statusClassMap = {
            'pending': 'status-pending',
            'in-transit': 'status-in-transit',
            'delivered': 'status-delivered',
            'cancelled': 'status-cancelled'
        };

        container.innerHTML = `
            <div class="card">
                <div class="card-header">
                    <h2>包裹详情</h2>
                </div>
                <div class="package-info">
                    <div class="info-row">
                        <span class="info-label">运单编号:</span>
                        <span class="info-value">${pkg.id}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">当前状态:</span>
                        <span class="info-value status-badge ${statusClassMap[pkg.status] || ''}">${this.getStatusText(pkg.status)}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">寄件人:</span>
                        <span class="info-value">${pkg.sender}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">收件人:</span>
                        <span class="info-value">${pkg.receiver}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">出发地:</span>
                        <span class="info-value">${pkg.origin}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">目的地:</span>
                        <span class="info-value">${pkg.destination}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">当前位置:</span>
                        <span class="info-value">${pkg.currentLocation}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">预计送达:</span>
                        <span class="info-value">${pkg.estimatedDelivery}</span>
                    </div>
                </div>
            </div>
        `;

        // 渲染状态更新表单
        this.renderUpdateForm(pkg.status);
    }

    // 渲染更新表单
    renderUpdateForm(currentStatus) {
        const container = document.getElementById('update-form');
        if (!container) return;

        // 状态选项
        let statusOptions = '';
        const statuses = [
            { value: 'pending', text: '待发货' },
            { value: 'in-transit', text: '运输中' },
            { value: 'delivered', text: '已送达' },
            { value: 'cancelled', text: '已取消' }
        ];

        // 根据当前状态过滤可用状态
        if (currentStatus === 'pending') {
            statusOptions = statuses.filter(s => s.value !== 'pending').map(s => `<option value="${s.value}">${s.text}</option>`).join('');
        } else if (currentStatus === 'in-transit') {
            statusOptions = statuses.filter(s => s.value === 'in-transit' || s.value === 'delivered' || s.value === 'cancelled').map(s => `<option value="${s.value}">${s.text}</option>`).join('');
        } else if (currentStatus === 'delivered' || currentStatus === 'cancelled') {
            statusOptions = `<option value="${currentStatus}" selected disabled>${this.getStatusText(currentStatus)}</option>`;
        }

        container.innerHTML = `
            <div class="card">
                <div class="card-header">
                    <h2>更新包裹状态</h2>
                </div>
                <form id="status-update-form">
                    <div class="form-group">
                        <label for="status">新状态</label>
                        <select id="status" name="status" class="form-control" ${(currentStatus === 'delivered' || currentStatus === 'cancelled') ? 'disabled' : ''}>
                            ${statusOptions}
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="location">当前位置</label>
                        <input type="text" id="location" name="location" class="form-control" placeholder="输入当前位置">
                    </div>
                    <div class="form-group">
                        <label for="description">备注</label>
                        <textarea id="description" name="description" class="form-control" rows="3" placeholder="输入备注信息"></textarea>
                    </div>
                    <button type="submit" class="btn-primary" ${(currentStatus === 'delivered' || currentStatus === 'cancelled') ? 'disabled' : ''}>更新状态</button>
                </form>
            </div>
        `;
    }

    // 绑定更新按钮事件
    bindUpdateButton(packageId) {
        const form = document.getElementById('status-update-form');
        if (!form) return;

        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            const status = document.getElementById('status').value;
            const location = document.getElementById('location').value;
            const description = document.getElementById('description').value;

            // 简单验证
            if (!location) {
                Utils.showNotification('请输入当前位置', 'warning');
                return;
            }

            try {
                // 显示加载状态
                this.showLoading(true);

                const response = await apiService.fetch('/api/packages', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        packageId,
                        status,
                        location,
                        description
                    })
                });

                if (response.success) {
                    Utils.showNotification('状态更新成功', 'success');
                    // 延迟后刷新页面
                    setTimeout(() => {
                        window.location.href = 'dashboard.html';
                    }, 1500);
                } else {
                    Utils.showNotification(response.message || '更新失败', 'error');
                }
            } catch (error) {
                console.error('更新状态失败:', error);
                Utils.showNotification('系统错误，请稍后再试', 'error');
            } finally {
                // 隐藏加载状态
                this.showLoading(false);
            }
        });
    }

    // 显示/隐藏加载状态
    showLoading(show) {
        const loadingElement = document.getElementById('loading');
        if (loadingElement) {
            loadingElement.style.display = show ? 'block' : 'none';
        }
    }

    // 获取状态文本
    getStatusText(status) {
        const statusMap = {
            'pending': '待发货',
            'in-transit': '运输中',
            'delivered': '已送达',
            'cancelled': '已取消'
        };
        return statusMap[status] || status;
    }
}

// 初始化模块
const courierUpdate = new CourierUpdate();

// 暴露到全局作用域
window.courierUpdate = courierUpdate;
    }
}

// 立即检查是否加载完成
initCourierUpdate();

// 如果未加载完成，延迟500ms后重试
if (!window.apiService || !window.Utils) {
    setTimeout(initCourierUpdate, 500);
}